/**
 * @Author: lifuzhao
 * @Date: 2019-07-12
 * @Project: driver
 */
import axios, {CancelToken} from "axios"
import store from '../vuex/index'
import router from '../router/index'
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || ''
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

let config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  // timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
}

const _axios = axios.create(config)
const _ajaxMap = {}
_axios.interceptors.request.use(
  function (config) {
    let {url} = config
    if (url !== '/api/v1/token/admin') {
      config.headers.token = store.state.token
    }
    if (config.abort) {
      _ajaxMap[url] && _ajaxMap[url]()
    }
    config.cancelToken = new CancelToken(excutor => _ajaxMap[url] = excutor)
    // Do something before request is sent
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  }
)

// Add a response interceptor
_axios.interceptors.response.use(
  function (response) {
    // Do something with response data
    let {config, data} = response
    if (data.errorCode) {
      data.success = false
      data.msg = data.msg ? '，失败原因：' + data.msg : ''
      if (data.errorCode === 10001) {
        router.push({
          path: '/login'
        })
      }
    } else {
      data = data.data || {}
      if (data.hasOwnProperty('success')) {
        data.successData = data.success
      }
      data.success = true
    }
    delete _ajaxMap[config.url]
    return data
  },
  function (error) {
    // Do something with response error
    return Promise.reject(error)
  }
)

_axios.install = function (Vue) {
  Vue.prototype.$axios = Vue.prototype.axios = _axios
}
export default _axios